<?php
/*
A command-line interface (CLI) utility designed to interpret user prompts and execute corresponding Linux commands. It processes user input, identifies the desired action, and provides instructions or executes the appropriate Linux command using the `shell_exec` function. The file includes a default system prompt to guide users in listing files, viewing file content, modifying file content, and deleting files, all while adhering to the specified format for input prompts.

Example:
$ php file_manager.php -p 'What are the files in the current directory?'
*/

require_once __DIR__ . '/function.php';

$systemPrompt = "You are an intelligent assistant that can help users list "
. "files, view file content, modify file content, and delete files. You need "
. "to identify the user's intention and include corresponding specific "
. "formatted instructions in the begin of your response, which are: " . PHP_EOL
. "- `[begin]ls \"dir\"[end]` List files in the given path directory `dir`." . PHP_EOL
. "- `[begin]cat \"file\"[end]` View the content of the given file `file`." . PHP_EOL
. "- `[begin]echo \"content\" >> \"file\"[end]` Modify the content of the given "
. "file `file` by appending the given content `content`." . PHP_EOL
. "- `[begin]rm \"file\"[end]` Delete the given file `file`." . PHP_EOL
. "These commands start with `[begin]` and end with `[end]`, parameters are "
. "enclosed in `\"\"`, and you only use one command at a time ("
. "That is to say, your reply cannot contain multiple instructions.)" . PHP_EOL
. "You cannot ask the user or content to replace parameters, you must choose "
. "a suitable Linux path or file name according to the user's intention as "
. "the parameter to replace it yourself." . PHP_EOL
. "If the user's request requires multiple instructions, you cannot output "
. "any instructions and need to tell the user to execute one action at a "
. "time, and guide the user on how to make the request to you.";

$args = getopt('p:');
$userPrompt = $args['p'] ?? '';

if (empty($userPrompt)) {
    fwrite(STDERR, 'No prompt.' . PHP_EOL);
    exit(1);
}

$output = runModel($userPrompt, $systemPrompt);

$matches = null;
preg_match_all('/\[begin\](.*?)\[end\]/s', $output, $matches, PREG_SET_ORDER);

if (empty($matches)) {
    fwrite(STDERR, 'Failed, I don\'t understand what you\'re saying.' . PHP_EOL);
    fwrite(STDERR, $output . PHP_EOL);
    exit(2);
}

$command = $matches[0][1];
echo $command . PHP_EOL;

echo "请检查此命令，如果你允许执行此命令请输入y并按回车键，否则输入其它退出：";

$handle = fopen('php://stdin', 'r');
$input = fgets($handle);
fclose($handle);
$input = rtrim($input);

if ($input !== 'y') {
    exit(0);
}

$bashExecutable = 'bash';
echo shell_exec("$bashExecutable -c " . escapeshellarg($command));

echo PHP_EOL;
